package com.yiqiu.common.core.util;

import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * 用于发起http请求的工具类
 *
 * @author weiyi
 */
public class HttpUtils {
    /**
     * 日志
     */
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
    /**
     * 请求客户端
     */
    private static final OkHttpClient CLIENT = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();
    /**
     * Get基本请求头
     */
    private static final Map<String, String> GET_HEADERS = Map.of(
            "Content-Type", "application/json",
            "Accept", "application/json",
            "User-Agent", "Mozilla/5.0"
    );

    private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");

    /**
     * 仅地址的Get请求
     * @param url 请求地址
     * @return
     */
    public static String sendGet(String url) {
       return sendGet(url,null,null);
    }

    /**
     *
     * @param url 请求地址
     * @param params 请求参数
     * @return
     */
    public static String sendGet(String url, Map<String, String> params) {
        return sendGet(url,params,null);
    }
    /**
     * 发送GET请求
     * @param url 请求地址
     * @param params URL查询参数
     * @param headers 自定义请求头，会与默认请求头合并
     * @return 响应体的字符串形式，如果请求失败则返回null
     */
    public static String sendGet(String url, Map<String, String> params, Map<String, String> headers) {
        if (url == null || "".equals(url)) {
            return "URL不能为空";
        }
        Request.Builder builder = new Request.Builder();

        Map<String, String> finalHeaders = new HashMap<>();
        finalHeaders.putAll(GET_HEADERS);
        if (headers != null) {
            finalHeaders.putAll(headers);
        }
        
        // 构建请求参数
        String finalUrl = url;
        if (params != null && !params.isEmpty()) {
            String paramStr = buildUrlParams(params);
            finalUrl = url + (url.contains("?") ? "&" : "?") + paramStr;
        }

        //构建请求
        builder.url(finalUrl).method("GET", null);
        //添加请求头
        finalHeaders.forEach(builder::header);
        try (Response response = CLIENT.newCall(builder.build()).execute()) {
            if (response.body() != null) {
                return response.body().string();
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 发送POST请求
     * @param url 请求地址
     * @return 响应体的字符串形式，如果请求失败则返回null
     */
    public static String sendPost(String url, Map<String, String> params) {
        return sendPost(url,params,null);
    }
    /**
     * 发送POST请求
     * @param url 请求地址
     * @return 响应体的字符串形式，如果请求失败则返回null
     */
    public static String sendPost(String url){
        return sendPost(url,null,null);
    }

    /**
     * 发送POST请求
     * @param url 请求地址
     * @param body 请求体参数，将会被转换为JSON格式
     * @param headers 自定义请求头，会与默认请求头合并
     * @return 响应体的字符串形式，如果请求失败则返回null
     */
    public static String sendPost(String url, Map<String, String> body, Map<String, String> headers) {
        if (url == null || "".equals(url)) {
            return "URL不能为空";
        }
        Request.Builder builder = new Request.Builder();
        // 合并默认请求头和自定义请求头
        Map<String, String> finalHeaders = new HashMap<>();
        finalHeaders.putAll(GET_HEADERS);
        if (headers != null) {
            finalHeaders.putAll(headers);
        }
        //请求体构建
        if (body != null && !body.isEmpty()) {
            String jsonString = JSONObject.toJSONString(body);
            builder.post(RequestBody.create(jsonString, JSON_TYPE));
        }
        //发送请求
        try(Response response = CLIENT.newCall(builder.build()).execute()) {
            if (response.body() != null) {
                return response.body().string();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 构建URL参数
     * @param params 参数Map
     * @return 格式化后的参数字符串
     */
    private static String buildUrlParams(Map<String, String> params) {
        if (params == null || params.isEmpty()) {
            return "";
        }
        StringBuilder paramBuilder = new StringBuilder();
        params.forEach((key, value) -> {
            if (paramBuilder.length() > 0) {
                paramBuilder.append("&");
            }
            paramBuilder.append(key).append("=").append(value);
        });
        return paramBuilder.toString();
    }


}
